<template>

  <el-card class="box-card">
    <div class="table-header">
      <div>
        <el-input
                style="width: 200px"
                v-model="urlParams.search"
                placeholder="请输入任务名称"
                clearable
                @clear="onSearch"
                @keyup.enter="onSearch"
        ></el-input>
        <el-button type="primary" style="margin-left: 10px" @click="onSearch"><el-icon><search /></el-icon>查询</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="SearchReset"><el-icon><RefreshRight /></el-icon>重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="createDialogVisible = true"><el-icon><plus /></el-icon>新增</el-button>
        <!--展示列弹出框-->
        <el-popover placement="left" :width="100" v-model:visible="columnVisible" trigger="contextmenu">
          <template #reference>
            <el-button type="primary" @click="columnVisible = true"><el-icon><setting /></el-icon>&nbsp;展示列</el-button>
          </template>
              <el-checkbox v-model="showColumn.name">任务名称</el-checkbox>
              <el-checkbox v-model="showColumn.command">脚本名称</el-checkbox>
              <el-checkbox v-model="showColumn.schedule">执行频率</el-checkbox>
<!--              <el-checkbox v-model="showColumn.server_ids">目标主机</el-checkbox>-->
              <el-checkbox v-model="showColumn.cron_script">脚本内容</el-checkbox>
              <el-checkbox v-model="showColumn.status">状态</el-checkbox>
              <el-checkbox v-model="showColumn.note">备注</el-checkbox>
              <el-checkbox v-model="showColumn.create_time">创建时间</el-checkbox>
              <el-checkbox v-model="showColumn.update_time">更新时间</el-checkbox>
            <div style="text-align: right; margin: 0">
              <el-button size="small" type="Default" @click="columnVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="saveColumn">确认</el-button>
            </div>

        </el-popover>

      </div>
    </div>

    <!--数据表格-->
    <el-table
            :data="tableData"
            style="width: 100%"
            stripe
            :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }"
            v-loading="loading"
            @cell-dblclick="dbclick"
            :show-overflow-tooltip="true"
            height="390px"
            :row-style="{height: '0'}"
            :cell-style="{padding: '4.7px',textAlign: 'center'}"
    >
        <template #empty><el-empty description="暂无数据" /></template>
        <el-table-column prop="name" label="任务名称"  v-if="showColumn.name"/>
        <el-table-column prop="command" label="脚本名称"  v-if="showColumn.command"/>
        <el-table-column prop="schedule" label="执行频率"  v-if="showColumn.schedule"/>
<!--        <el-table-column prop="server_ids" label="目标主机" width="120px" v-if="showColumn.server_ids"/>-->
        <el-table-column prop="cron_script" label="脚本内容"  v-if="showColumn.cron_script"/>
        <el-table-column prop="status" label="状态"  v-if="showColumn.status">
            <template #default="scope">
              <el-switch v-model="scope.row.status"
               inline-prompt @change="statusChangeHandle(scope.row)" active-text="启用"
               inactive-text="停用" :active-value="2" :inactive-value="1"></el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" v-if="showColumn.note"/>
        <el-table-column prop="create_time" label="创建时间"  sortable v-if="showColumn.create_time"/>
        <el-table-column prop="update_time" label="更新时间"  sortable v-if="showColumn.update_time"/>

      <!--操作栏-->
      <el-table-column fixed="right" label="操作" width="200px" >
        <template #default="scope">
          <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确定删除"
            @confirm="handleDel(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button type="danger" plain size="small">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button  type="info" plain size="small" @click="handleDesc(scope.$index, scope.row)">详情</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页-->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-card>

  <CronCreate v-model:visible="createDialogVisible"></CronCreate>
  <CronEdit v-model:visible="editDialogVisible" :row="row"></CronEdit>
  <CronDescribe v-model:visible="descDialogVisible" :row="row"></CronDescribe>

</template>

<script>
    import CronCreate from "./CronCreate.vue";
    import CronEdit from "./CronEdit.vue";
    import CronDescribe from "./CronDescribe.vue";
    export default {
        data() {
          return {
            loading: false,
            tableData: [],
            total: 0,  // 总数据条数
            pageSize: 10, // 默认每页的数据条数
            currentPage: 1,  // 默认开始页码
            urlParams: {  // URL查询参数
              page_num: 1,
              page_size: 10,
              search: ''
            },
            editDialogVisible: false,
            descDialogVisible: false,
            row: '',
            createDialogVisible: false,
            showColumn: {
              name: true,
              command: true,
              schedule: true,
              server_ids: true,
              cron_script: true,
              status: true,
              note: true,
              create_time: true,
              update_time: true
            },
            columnVisible: false // 展示与隐藏
          }
        },
        mounted() {
          this.getData();
          // 从浏览器本地存储获取历史展示列
          const columnSet = localStorage.getItem(this.$route.path + '-columnSet')
          // 如果本地有存储则使用
          if(columnSet) {
            this.showColumn = JSON.parse(columnSet)
          }
        },
        methods: {
          getData() {
            this.loading = true;
            this.$http.get('/task/cron/', {params: this.urlParams})
              .then(res => {
                this.tableData = res.data.data;
                this.total = res.data.count;
                this.loading = false;
              })
          },
           // 分页：监听【选择每页数量】的事件
          handleSizeChange(pageSize) {
              // console.log(pageSize)
              this.pageSize = pageSize; // 重新设置分页显示
              this.urlParams.page_size = pageSize;  // 将最新值设置到数据里，用于下面用新值重新获取数据
              this.getData()
          },
          // 分页：监听【点击页码】的事件
          handleCurrentChange(currentPage) {
              // console.log(currentPage)
              this.currentPage = currentPage; // 重新设置分页显示
              this.urlParams.page_num = currentPage;
              this.getData()
          },
          handleEdit(index, row) {
            // console.log(index,row);
            this.editDialogVisible = true;
            this.row = row;
          },
          handleDesc(index, row) {
            // console.log(index,row);
            this.descDialogVisible = true;
            this.row = row;
          },
          statusChangeHandle(row) {
            this.$http.put('/cron_enable/', row, {timeout: 60000})
            .then(res => {
                if(res.data.code === 200) {
                    this.$message.success(res.data.msg);
                } else {
                    this.$message.error(res.data.msg);
                }
            })
            .catch(() => {

            })
          },
          //双击显示详情
          dbclick(row, column, cell, event){
            this.descDialogVisible = true;
            this.row = row;
          },
          handleDel(index, row) {
              this.$http.delete('/task/cron/'+ row.id + '/')
                  .then(res => {
                    if(res.data.code === 200) {
                      this.$message.success('删除成功');
                      this.tableData.splice(index, 1); // 根据表格索引临时删除数据
                    } else {
                      this.$message.error(res.data.msg);
                    }
                  })
                .catch(() => {
                  // this.$message.info('取消');
                })
          },
          onSearch() {
            this.getData();
          },
          //重置查询的数据
          SearchReset() {
            this.urlParams.search = '';
            this.getData();
          },
          saveColumn() {
            localStorage.setItem(this.$route.path + '-columnSet', JSON.stringify(this.showColumn));
            this.columnVisible = false;
          }
        },
        components: {
          CronCreate,
          CronEdit,
          CronDescribe
        }
    }
</script>

<style scoped>
  .table-header {
    display: flex;
    margin-bottom: 18px;
    justify-content: space-between;
  }
</style>